//
//  WAVFileWriter.m
//  record_plugin
//
//  Created by zqj on 2024/9/12.
//

#import "WAVFileWriter.h"

@implementation WAVFileWriter

- (void)writeWAVFileFromPCMData:(NSData *)pcmData
                    sampleRate:(int)sampleRate
                     numChannels:(short)numChannels
                     outputPath:(NSString *)outputPath {
    
    // WAV 文件头信息
    NSUInteger pcmDataSize = pcmData.length;
    NSUInteger byteRate = sampleRate * numChannels * sizeof(int16_t); // int16_t 为 2 字节

    // 文件头长度
    NSUInteger totalSize = 36 + pcmDataSize;
    
    // 创建文件头
    NSMutableData *wavHeader = [NSMutableData dataWithLength:44];
    
    // RIFF Header
    [wavHeader replaceBytesInRange:NSMakeRange(0, 4) withBytes:"RIFF" length:4];
    [wavHeader replaceBytesInRange:NSMakeRange(4, 4) withBytes:&totalSize length:4];
    [wavHeader replaceBytesInRange:NSMakeRange(8, 4) withBytes:"WAVE" length:4];
    
    // fmt subchunk
    [wavHeader replaceBytesInRange:NSMakeRange(12, 4) withBytes:"fmt " length:4];
    NSUInteger fmtChunkSize = 16; // PCM 格式的 fmt 长度
    [wavHeader replaceBytesInRange:NSMakeRange(16, 4) withBytes:&fmtChunkSize length:4];
    
    short audioFormat = 1; // PCM
    [wavHeader replaceBytesInRange:NSMakeRange(20, 2) withBytes:&audioFormat length:2];
    [wavHeader replaceBytesInRange:NSMakeRange(22, 2) withBytes:&numChannels length:2];
    [wavHeader replaceBytesInRange:NSMakeRange(24, 4) withBytes:&sampleRate length:4];
    [wavHeader replaceBytesInRange:NSMakeRange(28, 4) withBytes:&byteRate length:4];
    
    short blockAlign = numChannels * sizeof(int16_t); // 2 字节 per sample
    [wavHeader replaceBytesInRange:NSMakeRange(32, 2) withBytes:&blockAlign length:2];
    
    short bitsPerSample = 16; // 16 bit
    [wavHeader replaceBytesInRange:NSMakeRange(34, 2) withBytes:&bitsPerSample length:2];
    
    // data subchunk
    [wavHeader replaceBytesInRange:NSMakeRange(36, 4) withBytes:"data" length:4];
    [wavHeader replaceBytesInRange:NSMakeRange(40, 4) withBytes:&pcmDataSize length:4];
    
    // 创建并写入 WAV 文件
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:outputPath];
    if (!fileHandle) {
        [[NSFileManager defaultManager] createFileAtPath:outputPath contents:nil attributes:nil];
        fileHandle = [NSFileHandle fileHandleForWritingAtPath:outputPath];
    }
    
    // 写入文件头及PCM数据
    [fileHandle writeData:wavHeader];
    [fileHandle writeData:pcmData];
    
    // 关闭文件
    [fileHandle closeFile];
}  

@end
